{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Visualize Taxonomy\n",
    "\n",
    "We use the [*networkx*](https://networkx.github.io/) Python package for analyzing graphs and the [*graphviz*](https://graphviz.readthedocs.io/) Python package for drawing graphs.\n",
    "\n",
    "See http://www.graphviz.org/doc/info/attrs.html for a description of the different graphviz attributes."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "%load_ext autoreload\n",
    "%autoreload 2\n",
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "from typing import Any, Mapping, Tuple\n",
    "\n",
    "import graphviz as gv\n",
    "import networkx as nx\n",
    "import pandas as pd\n",
    "\n",
    "from taxonomy_mapping.taxonomy_graph import TaxonNode, build_taxonomy_graph"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "TAXONOMY_CSV_PATH = r'g:/temp/lila/lila-taxonomy-mapping_release.csv'\n",
    "OUTPUT_FOLDER = r'g:\\temp'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Load taxonomy CSV"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "df = pd.read_csv(TAXONOMY_CSV_PATH)\n",
    "display(df.head())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Show rows without a taxonomy string"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# This should just be things like \"end\" and \"fire\"\n",
    "\n",
    "with pd.option_context('display.max_rows', 100):\n",
    "     display(df[df['taxonomy_string'].isna()])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Build the taxonomy graph"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "graph, taxon_to_node, label_to_node = build_taxonomy_graph(df)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Graph helper methods"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "def nx_to_gv(nx_g: nx.DiGraph, vert_spacing: float = 0.5) -> gv.Digraph:\n",
    "    \"\"\"Converts a networkX graph to a graphviz graph.\"\"\"\n",
    "    gv_g = gv.Digraph(\n",
    "        graph_attr=dict(overlap='false', concentrate='true', ranksep=str(vert_spacing)),\n",
    "        node_attr=dict(margin='0', width='0', height='0'))\n",
    "    for n in nx_g.nodes:  # each node is a TaxonNode\n",
    "        gv_g.node(f'{n.level}\\n{n.name}')\n",
    "    for n1, n2 in nx_g.edges:\n",
    "        n1_id = f'{n1.level}\\n{n1.name}'\n",
    "        n2_id = f'{n2.level}\\n{n2.name}'\n",
    "        gv_g.edge(n1_id, n2_id)\n",
    "    return gv_g\n",
    "\n",
    "\n",
    "def visualize_subgraph(nx_graph: nx.DiGraph, node: Any,\n",
    "                       vert_spacing: float = 0.5) -> gv.Digraph:\n",
    "    \"\"\"Returns a gv.Digraph rooted at node.\"\"\"\n",
    "    nx_subgraph_nodes = nx.descendants(nx_graph, node) | {node}\n",
    "    nx_subgraph = nx_graph.subgraph(nx_subgraph_nodes)\n",
    "    gv_subgraph = nx_to_gv(nx_subgraph, vert_spacing=vert_spacing)\n",
    "    return gv_subgraph"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Render entire Taxonomy graph to SVG\n",
    "\n",
    "May include disconnected components."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "gv_g = nx_to_gv(graph, vert_spacing=1.5)\n",
    "gv_g.render(os.path.join(OUTPUT_FOLDER,'taxonomy-rendering'), format='svg', cleanup=True)\n",
    "gv_g.render(os.path.join(OUTPUT_FOLDER,'taxonomy-rendering'), format='jpg', cleanup=True)\n",
    "gv_g.render(os.path.join(OUTPUT_FOLDER,'taxonomy-rendering'), format='pdf', cleanup=True)\n",
    "# display(gv_g)  # this can be huge"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Analyze Taxonomy graph"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print('Total number of nodes:', len(graph.nodes))\n",
    "print('Number of disconnected components:', nx.number_weakly_connected_components(graph))\n",
    "\n",
    "for subgraph in nx.weakly_connected_components(graph):\n",
    "    # each subgraph is a set of (taxon_level, taxon_name)\n",
    "\n",
    "    # get root node\n",
    "    subgraph = graph.subgraph(subgraph)\n",
    "    root_nodes = [n for n, d in subgraph.in_degree() if d==0]\n",
    "    assert len(root_nodes) == 1\n",
    "    root_node = root_nodes[0]\n",
    "\n",
    "    print(f'Graph rooted at {root_node} has {len(subgraph.nodes)} nodes')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Display disconnected component"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "gv_g = visualize_subgraph(graph, node=taxon_to_node[('phylum', 'tracheophyta')],\n",
    "                          vert_spacing=0.2)\n",
    "display(gv_g)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Query the graph"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Show the smallest subgraph containing all given dataset labels"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "labels = [\n",
    "    ('Idaho Camera Traps', 'mountain_lion'),\n",
    "    ('Idaho Camera Traps', 'bobcat'),\n",
    "    ('Idaho Camera Traps', 'cat_domestic'),\n",
    "    ('Idaho Camera Traps', 'lynx'),\n",
    "    ('Idaho Camera Traps', 'lion')\n",
    "]\n",
    "nodes = [label_to_node[label] for label in labels]\n",
    "lca_node = TaxonNode.lowest_common_ancestor(set(nodes))\n",
    "assert lca_node is not None\n",
    "print(lca_node)\n",
    "gv_g = visualize_subgraph(graph, node=taxon_to_node[(lca_node.level, lca_node.name)],\n",
    "                          vert_spacing=0.5)\n",
    "display(gv_g)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Get the set of dataset labels corresponding to this subgraph"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "lca_node.get_dataset_labels()"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.9.7"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
